<template>
  <div class="main">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd">
              <IconifyIconOffline icon="ep:plus" />
              新增用户
            </el-button>
          </div>
        </div>
      </template>

      <div class="content">
        <!-- 搜索区域 -->
        <div class="search-container">
          <el-form :model="searchForm" inline>
            <el-form-item label="姓名">
              <el-input
                v-model="searchForm.name"
                placeholder="请输入姓名"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <IconifyIconOffline icon="ep:search" />
                搜索
              </el-button>
              <el-button @click="handleReset">
                <IconifyIconOffline icon="ep:refresh-left" />
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 用户列表表格 -->
        <el-table
          v-loading="loading"
          :data="userList"
          border
          stripe
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" width="80" />

          <el-table-column prop="name" label="姓名" min-width="120" />

          <el-table-column prop="rname" label="角色" min-width="120">
            <template #default="{ row }">
              <span>{{ row.rname || "-" }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="phone" label="手机号" min-width="140" />

          <el-table-column prop="email" label="邮箱" min-width="180" />

          <el-table-column prop="imageUrl" label="头像" width="80">
            <template #default="{ row }">
              <el-avatar :size="28" :src="row.imageUrl" />
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" min-width="180">
            <template #default="{ row }">
              <span>{{ formatDate(row.createTime) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="220" fixed="right">
            <template #default="{ row }">
              <el-button type="success" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button
                type="warning"
                size="small"
                @click="openRoleDialog(row)"
              >
                分配角色
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.limit"
            :page-sizes="[5, 10, 20, 50]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="520px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="formData.email" 
            placeholder="请输入邮箱" 
            prefix-icon="Message"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="头像" prop="imageUrl">
          <el-upload
            class="avatar-uploader"
            :http-request="customAvatarRequest"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            accept="image/png,image/jpeg,image/jpg,image/webp"
          >
            <img
              v-if="formData.imageUrl"
              :src="formData.imageUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button :loading="submitLoading" type="primary" @click="handleSubmit"
          >确定</el-button
        >
      </template>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      title="分配角色"
      width="520px"
      :close-on-click-modal="false"
    >
      <div v-loading="roleLoading">
        <el-form label-width="100px">
          <el-form-item label="管理员">
            <span>{{ currentRoleAdmin?.name || "-" }}</span>
          </el-form-item>
          <el-form-item label="选择角色">
            <el-select
              v-model="selectedRoleIds"
              multiple
              placeholder="请选择角色"
              style="width: 100%"
            >
              <el-option
                v-for="item in roleOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button
          :loading="roleSubmitLoading"
          type="primary"
          @click="submitRole"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps, UploadRequestOptions } from "element-plus";
import {
  getAdminList,
  createAdmin,
  updateAdmin,
  deleteAdmin,
  updateAdminRole,
  type AdminItem
} from "@/api/admin";
import { getRoleList, type RoleItem } from "@/api/role";
import { uploadImage } from "@/api/upload";

defineOptions({
  name: "SystemUser"
});

// 响应式数据
const loading = ref(false);
const userList = ref<AdminItem[]>([]);
const dialogVisible = ref(false);
const submitLoading = ref(false);
const isEdit = ref(false);
const currentEditId = ref<number | null>(null);

// 分页数据
const pagination = reactive({
  page: 1,
  limit: 5,
  total: 0
});

// 搜索表单
const searchForm = reactive({
  name: ""
});

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return "-";
  const date = new Date(dateString);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit"
  });
};

// 获取用户列表
const fetchUserList = async () => {
  try {
    loading.value = true;
    const data = {
      page: pagination.page,
      limit: pagination.limit,
      ...(searchForm.name && { name: searchForm.name })
    };
    const res = await getAdminList(data);
    if (res.code === 0) {
      userList.value = res.data.list;
      pagination.total = res.data.total;
    }
  } catch (error) {
    ElMessage.error("获取用户列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  fetchUserList();
};

// 重置
const handleReset = () => {
  searchForm.name = "";
  pagination.page = 1;
  fetchUserList();
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.limit = size;
  pagination.page = 1;
  fetchUserList();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  fetchUserList();
};

onMounted(() => {
  fetchUserList();
});

// 新增
const handleAdd = () => {
  isEdit.value = false;
  currentEditId.value = null;
  resetForm();
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row: AdminItem) => {
  isEdit.value = true;
  currentEditId.value = row.id;
  Object.assign(formData, row);
  dialogVisible.value = true;
};

// 删除
const handleDelete = async (row: AdminItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.name}" 吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );
    await deleteAdmin(row.id);
    ElMessage.success("删除成功");
    fetchUserList();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 分配角色对话框相关
const roleDialogVisible = ref(false);
const roleLoading = ref(false);
const roleSubmitLoading = ref(false);
const roleOptions = ref<RoleItem[]>([]);
const selectedRoleIds = ref<number[]>([]);
const currentRoleAdmin = ref<AdminItem | null>(null);

const openRoleDialog = async (row: AdminItem) => {
  currentRoleAdmin.value = row;
  roleDialogVisible.value = true;
  selectedRoleIds.value = [];
  try {
    roleLoading.value = true;
    const res = await getRoleList({ page: 1, limit: 9999 });
    if (res.code === 0) {
      roleOptions.value = res.data.list || [];
    }
  } catch (e) {
    ElMessage.error("获取角色列表失败");
  } finally {
    roleLoading.value = false;
  }
};

const submitRole = async () => {
  if (!currentRoleAdmin.value) return;
  try {
    roleSubmitLoading.value = true;
    await updateAdminRole({
      adminId: currentRoleAdmin.value.id,
      roleIds: selectedRoleIds.value
    });
    ElMessage.success("分配角色成功");
    roleDialogVisible.value = false;
    fetchUserList();
  } catch (e) {
    ElMessage.error("分配角色失败");
  } finally {
    roleSubmitLoading.value = false;
  }
};

// 表单
import type { FormInstance, FormRules } from "element-plus";
const formRef = ref<FormInstance>();
const formData = reactive<Partial<AdminItem>>({
  name: "",
  username: "",
  phone: "",
  email: "",
  imageUrl: ""
});

// 邮箱格式正则表达式
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

const formRules: FormRules = {
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  email: [
    {
      pattern: emailRegex,
      message: "请输入正确的邮箱格式",
      trigger: "blur",
      required: false
    }
  ]
};

const resetForm = () => {
  Object.assign(formData, {
    name: "",
    username: "",
    phone: "",
    email: "",
    imageUrl: ""
  });
  formRef.value?.clearValidate();
};

const dialogTitle = computed(() => (isEdit.value ? "编辑用户" : "新增用户"));

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    submitLoading.value = true;
    if (isEdit.value) {
      await updateAdmin(currentEditId.value!, formData);
      ElMessage.success("编辑成功");
    } else {
      const payload = {
        name: formData.name!,
        username: formData.username,
        phone: formData.phone,
        email: formData.email,
        imageUrl: formData.imageUrl
      };
      await createAdmin(payload);
      ElMessage.success("新增成功");
    }
    dialogVisible.value = false;
    fetchUserList();
  } catch (error) {
    ElMessage.error(isEdit.value ? "编辑失败" : "新增失败");
  } finally {
    submitLoading.value = false;
  }
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = rawFile => {
  const isImage = [
    "image/jpeg",
    "image/png",
    "image/jpg",
    "image/webp"
  ].includes(rawFile.type);
  if (!isImage) {
    ElMessage.error("仅支持 jpg/png/webp 格式");
    return false;
  }
  const isLt2M = rawFile.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB");
    return false;
  }
  return true;
};

// 自定义上传
const customAvatarRequest = async (options: UploadRequestOptions) => {
  try {
    const raw = options.file as File;
    const res = await uploadImage(raw);
    if (res.code === 0 && res.data) {
      formData.imageUrl = res.data;
      options.onSuccess?.(res as any);
    } else {
      ElMessage.error(res.message || "上传失败");
      options.onError?.(new Error(res.message || "上传失败") as any);
    }
  } catch (e: any) {
    ElMessage.error(e?.message || "上传失败");
    options.onError?.(e as any);
  }
};

// 预览
const avatarPreviewVisible = ref(false);
const avatarPreviewUrl = ref<string>("");
const handleAvatarPreview: UploadProps["onPreview"] = file => {
  const url = (file as any).url || (file as any).response?.data;
  if (url) {
    avatarPreviewUrl.value = url as string;
    avatarPreviewVisible.value = true;
  }
};
</script>

<style scoped>
.main {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.content {
  padding: 20px 0;
}

.search-container {
  padding: 16px;
  margin-bottom: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

:deep(.el-table) {
  .el-table__row {
    .el-table__cell {
      padding: 8px 0;
    }
  }
}

.avatar-uploader .avatar {
  display: block;
  width: 178px;
  height: 178px;
}

:deep(.avatar-uploader .el-upload) {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 178px;
  height: 178px;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  width: 100%;
  height: 100%;
  font-size: 28px;
  line-height: 178px;
  color: #8c939d;
  text-align: center;
}
</style>
